#encoding: utf-8
class Motorcade < BizUnit
  has_many :vehicles

  def vehicle_in_range_from_mc gps_range
    return nil if gps_range == nil
    mc = Opal::Mc::Mc.new("VEHICLE_MC")
    rst = {}
    self.vehicles.each do|vehicle|
      vehicle_no = vehicle.vehicle_no
      gps_in_mc = mc.get(vehicle_no)
      if gps_in_mc
        gps ={:lat => gps_in_mc.lat, :lng => gps_in_mc.lng}
        logger.debug "--------------#{gps_in_mc.methods}"
        if in_gps_range(gps, gps_range)
          gps_in_mc.update(:bl_no => vehicle.bl_no)
          rst[vehicle_no] =gps_in_mc
        end
      end
    end
    return rst
  end

  #gps坐标是否在给定的范围内
  def in_gps_range(gps,  gps_range)
      if gps and gps_range
        if gps[:lat] >= gps_range[:lat][0] and gps[:lat] <= gps_range[:lat][1] and  gps[:lng]>= gps_range[:lng][0] and gps[:lng] <= gps_range[:lng][1]
          return true
        end
      end
    return false
  end

  def check_data?(data)
     #todo校验
     return true
   end

   # 解析数据
   # 所需数据: motorcade_code, bl_no, ctn_no, vehicle_no, driver, destination, phone_no, group_name, send_time
   def read_datagram(data_arr)
     if check_data?(data_arr)
       data_arr.each do |data|
         case data["command"].to_s
           when "order_vehicle"
             bl = Bl.find_by_bl_no(data['bl_no'])
             if bl
               bl.send_car(data['ctn_no'], data['vehicle_no'])
               vehicle = Vehicle.find_by_vehicle_no(data["vehicle_no"])
               if !vehicle
                 vehicle = Vehicle.create(:vehicle_no => data['vehicle_no'], :driver_name => data['driver'], :destination => data['destination'],
                                          :driver_phone => data['phone_no'], :motor_cade_id => self.id, :groups => data['group_name'], :bl_no => data['bl_no'],
                                          :require_arrive_time => data['require_arrive_time'])
               else
                 vehicle.update_attribute(:destination, data['destination'])
                 vehicle.update_attribute(:bl_no, data['bl_no'])
                 vehicle.update_attribute(:require_arrive_time, data['require_arrive_time'])
               end
               # 保存历史纪录
               VehiclesHistory.create(:vehicle_no => data['vehicle_no'],
                                      :send_time => data['send_time'],
                                      :destination => data['destination'],
                                      :require_arrive_time => data['require_arrive_time'],
                                      :vehicle_id => vehicle.id)
             else
               logger.error "no such bl with bl_no:'#{data['bl_no']}'"
             end
             logger.debug "派车成功--succeed send_car!"
           else
             logger.debug "wrong command!"
         end
       end
     end
   end

end
